package com.ecoolex.chinadutyfree.retailer.job.scheduler;

import java.util.Calendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.ecoolex.chinadutyfree.retailer.core.CoreConstant;
import com.ecoolex.chinadutyfree.retailer.core.manager.DirectMailGoodsOrderManager;
import com.ecoolex.chinadutyfree.retailer.entity.DirectMailGoodsOrder;
import com.ecoolex.framework.modularize.api.service.config.SystemConfig;
import com.ecoolex.framework.scheduler.Job;
import com.ecoolex.framework.scheduler.JobComponent;

@JobComponent
public class DirectMailGoodsOrderCheckJob {

	private static final Logger log = LoggerFactory.getLogger(DirectMailGoodsOrderCheckJob.class);
	
	@Autowired
	private SystemConfig systemConfig;
	
	@Autowired
	private DirectMailGoodsOrderManager directMailGoodsOrderManager;
	
	@Job(name = "chinadutyfree.DirectMailGoodsOrderCheckJob.autoCloseOrder", describe = "自动关闭未支付的直邮商品订单")
	public void autoCloseOrder() {
		// 订单超时时间 (分钟)
		String minutesStr = systemConfig.get(CoreConstant.CONFIG_CHINADUTYFREE_RETAILER_ORDER_AUTO_CANCEL_MINUTES);
		int minutes = Integer.valueOf(minutesStr);

		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MINUTE, -minutes);
		
		List<DirectMailGoodsOrder> orderList
		= directMailGoodsOrderManager.queryUnpaidAndExpiration(calendar.getTime(), 10);
		// 自动取消订单
		orderList.forEach(order -> {
			try {
				directMailGoodsOrderManager.autoCancel(order, this.getClass().getSimpleName());
			} catch (Exception e) {
				log.error("自动关闭未支付的直邮商品订单异常. orderId={}", order.getOrderId(), e);
			}
		});
	}
	
	@Job(name = "chinadutyfree.DirectMailGoodsOrderCheckJob.autoConfirmReceipt", describe = "自动确认直邮商品订单收货")
	public void autoConfirmReceipt() {
		// 订单收货超时时间 (天)
		String dayStr = systemConfig.get(CoreConstant.CONFIG_CHINADUTYFREE_RETAILER_ORDER_AUTO_CONFIRM_RECEIVED_DAY);
		int day = Integer.valueOf(dayStr);

		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -day);
		
		List<DirectMailGoodsOrder> orderList
		= directMailGoodsOrderManager.queryShippedAndExpiration(calendar.getTime(), 10);
		// 自动确认收货
		orderList.forEach(order -> {
			try {
				directMailGoodsOrderManager.confirmReceipt(order, this.getClass().getSimpleName());
			} catch (Exception e) {
				log.error("自动确认直邮商品订单收货异常. orderId={}", order.getOrderId(), e);
			}
		});
	}
}
